<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="单位名称" prop="unitId">
        <el-select
          v-model="queryParams.unitId"
          placeholder="单位名称"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in unitOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处罚类型" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="处罚类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in violaOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处罚部门" prop="deptId">
        <treeselect 
          v-model="queryParams.deptId" 
          :options="deptOptions" 
          :show-count="true" 
          placeholder="请选择处罚部门" 
          style="width: 240px"
          size="small"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          placeholder="请输入姓名/手机号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['61110']"
          @click="handleAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >批量导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> 

    <el-table v-loading="loading" :data="tableList" :border="true">
      <el-table-column label="单位名称" prop="workUnit" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="人员姓名" prop="personnel" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="性别" prop="genderVal" align="center" />
      <el-table-column label="手机号" prop="phone" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="工种" prop="workType" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="处罚类型" prop="category" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="处罚内容" prop="situationDescription" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="处罚日期" prop="punishmentTime" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="处罚部门" prop="department0" align="center" />
      <el-table-column label="发布人" prop="reviewer" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="发布时间" prop="reviewTime" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['61120']"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['61130']"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetial(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pagesize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <!-- *单位名称（下拉框）、人员姓名(下拉框)、性别、手机号、工种、*处罚类型、*处罚内容、*处罚日期、*处罚部门 -->
      <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false" label-width="80px">
        <el-form-item label="处罚部门" prop="departmentId0">
          <treeselect v-model="form.departmentId0" :options="deptOptions" @select="selectTree" :show-count="true" placeholder="请选择处罚部门" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="unitId">
              <el-select v-model="form.unitId" @change="changeUnit" placeholder="请选择">
                <el-option
                  v-for="item in unitOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 添加 -->
            <el-form-item v-if="!form.theid" label="姓名" prop="personnelId">
              <el-select 
                v-model="form.personnelId" 
                placeholder="请选择" 
                filterable
                :filter-method="dataFilter"
                @change="changePersonnel"
              >
                <el-option 
                  v-for="item in personnelOptions" 
                  :key="item.theid" 
                  :label="item.fullName" 
                  :value="item.theid"
                >
                  <span style="float: left">{{ item.fullName }}</span>
                  <span style="float: right; margin-left: 10px; color: #8492a6; font-size: 13px">
                    {{ item.department }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 修改 -->
            <el-form-item v-if="form.theid" label="姓名" prop="personnel">
              <el-input v-model="form.personnel" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="genderId">
              <el-radio-group v-model="form.genderId" @change="changeGender">
                <el-radio 
                  v-for="item in genderOptions"
                  :key="item.id"
                  :value="item.id"
                  :label="item.id"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工种" prop="workIds">
              <el-select
                v-model="form.workIds"
                multiple
                placeholder="请选择"
                @change="changeWork"
              >
                <el-option
                  v-for="item in workOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处罚类型" prop="categoryId">
              <el-select v-model="form.categoryId" @change="changeCate" placeholder="请选择">
                <el-option
                  v-for="item in violaOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处罚内容" prop="situationDescription">
              <el-input v-model="form.situationDescription" placeholder="请输入处罚内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处罚日期" prop="punishmentTime">
              <el-date-picker clearable size="small"
                v-model="form.punishmentTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择处罚日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 点击详情，显示处罚记录详情 -->
    <el-dialog
      title="处罚记录详情"
      :visible.sync="openDetail"
      width="600px"
      append-to-body
    >
      <el-form
        ref="detailForm"
        :model="detailForm"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="workUnit">
              <el-input v-model="detailForm.workUnit" disabled />
            </el-form-item>

            <el-form-item label="人员姓名" prop="personnel">
              <el-input v-model="detailForm.personnel" disabled />
            </el-form-item>

            <el-form-item label="性别" prop="genderVal">
              <el-input v-model="detailForm.genderVal" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个人照片" prop="avatar">
              <uploadImage v-model="detailForm.avatar" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="人员姓名" prop="personnel">
              <el-input v-model="detailForm.personnel" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="genderVal">
              <el-input v-model="detailForm.genderVal" disabled />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="detailForm.phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工种" prop="workType">
              <el-input v-model="detailForm.workType" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处罚类型" prop="category">
              <el-input v-model="detailForm.category" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处罚内容" prop="situationDescription">
              <el-input v-model="detailForm.situationDescription" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处罚日期" prop="violationTime">
              <el-input v-model="detailForm.violationTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处罚部门" prop="department0">
              <el-input v-model="detailForm.department0" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import UploadImage from '@/components/ImageUpload';

import { getPage, listData, getData, delData, addData, updateData, getSelect } from "@/api/punish/punish";
import { listData as personListData } from "@/api/system/personAdmin";
import { getDepartment, getDict ,getDataListGender } from "@/api/select";

export default {
  name: "punish",
  data() {
    return {
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        categoryId: undefined,
        unitId: undefined,
        deptId: undefined,
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        phone: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" },
        ],
        unitId: [
          { required: true, message: "请选择单位名称", trigger: "change" },
        ],
        genderId: [
          { required: true, message: "请选择性别", trigger: "change" },
        ],
        categoryId: [
          { required: true, message: "请选择处罚类型", trigger: "change" },
        ],
        situationDescription: [
          { required: true, message: "处罚内容不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "请选择处罚日期", trigger: "change" },
        ],
        departmentId0: [
          { required: true, message: "请选择处罚部门", trigger: "blur" },
        ]
      },
      openDetail: false,
      detailForm: {},
      genderOptions: [],
      workOptions: [], 
      violaOptions: [],  //违章违规类别
      deptOptions: [],   //所属部门
      unitOptions: [],  //工作单位
      personnelOptions: [],  //人员
      personnelOptions2: [],  //人员
      personQueryParams: {
        currentPage: 1,
        pagesize: 100000,
        deptId: undefined,
        workIds: undefined,
        workType: undefined,
        post: undefined,
        keywords: undefined,
      },
    }
  },
  components: {
    Treeselect,
    UploadImage
  },
  created() {
    this.getList();
    this.getSelect();
    this.getPersonnelOptions()
  },
  mounted() {
    
  },
  methods: {
    getList() {
      this.loading = true;
      listData(this.queryParams).then( response => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    getSelect() {
      getSelect().then((response) => {
        this.violaOptions = response.result.violationCategory;  //违章违规类别
        // this.deptOptions = response.result.departmentInfo;   //所属部门
        this.unitOptions = response.result.institutionsInfo;  //工作单位
      });
      getDepartment().then( response => {
        this.deptOptions =  response.result.data; 
      });
      getDataListGender().then( response => { //性别
        this.genderOptions = response.result.data;
      });
      // 获取数据字典
      getDict(12, 0).then( response => { //12-工种
        this.workOptions =  response.result.data;
      });
    },
    getPersonnelOptions() {
      personListData(this.personQueryParams).then((response) => {
        this.personnelOptions = response.result.rows;
        this.personnelOptions2 = response.result.rows;
      });
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetial(row) {
      this.detailForm = {}
      const theId = row.theid
      getData(theId).then(response => {
        this.detailForm = response.result[0];
        this.openDetail = true
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.theid
      getData(theId).then(response => {
        console.log('response',response.result)
        this.form = response.result[0];
        // let arr = response.result.workTypeId.split(',');
        // this.form.workTypeId = arr.map(item => { return Number(item) })
        this.form.workIds = Array.of(response.result[0].workTypeId)
        this.changeWork(this.form.workIds)
        this.form = {...this.form}
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      console.log('this.form',this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then(response => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        departmentId0: null,
        unitId: null,
        personnelId: null,
        genderId: null,
        phone: null,
        personnelType: 1, //违规人类型 1-内部员工 2-外委人员
        workTypeId: [],
        workIds: [],
        situationDescription: null,
        punishmentTime: ''
      };
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.theid
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          // 调接口
          return delRole(theId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm('是否确认导出?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(function() {
          // 调接口导出表
          // return exportRole(queryParams);
      }).then(response => {
          this.download(response.msg);
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    selectTree(val) {
      if (this.deptOptions.length>0) {
        this.form.department0 = val.label
      }
    },
    changeUnit(val) {
      if (this.unitOptions.length>0) {
        this.form.workUnit = val ? this.unitOptions.find(ele => ele.id === val).label: ''
      }
    },
    changeCate(val) {
      if (this.violaOptions.length>0) {
        this.form.category = val ? this.violaOptions.find(ele => ele.id === val).label: ''
      }
    },
    dataFilter(val) {
      this.value = val;
      if (val) { //val存在
        this.personnelOptions = this.personnelOptions2.filter((item) => {
          if (!!~item.fullName.indexOf(val) || !!~item.fullName.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { //val为空时，还原数组
        this.personnelOptions = this.personnelOptions2;
      }
    },
    changePersonnel(val) {
      if (this.personnelOptions2.length>0) {
        this.form.personnel = val ? this.personnelOptions2.find(ele => ele.theid === val).fullName: ''
        this.personnelOptions = this.personnelOptions2
      }
    },
    changeGender(val) {
      if (this.genderOptions.length>0) {
        this.form.genderVal = val ? this.genderOptions.find(ele => ele.id === val).label: ''
      }
    },
    changeWork(val) {
      let workIdsArr = [], workValArr = [];
      for(let i=0;i<=val.length-1;i++){
        this.workOptions.find((item)=>{ 
          if(item.id == val[i]){
            workIdsArr.push(item.id) 
            workValArr.push(item.label)
          }
        });
      }
      this.form.workTypeId = workIdsArr.join(',')
      this.form.workType = workValArr.join(',')
      console.log(this.form.workIds)
    },
  }
};
</script>

<style scoped lang="scss">
/* .el-date-editor*/
/deep/ .el-dialog__body .el-date-editor.el-input,
/deep/ .el-dialog__body .el-date-editor.el-input__inner {
  // width: 220px;
  width: auto !important;
}
</style>
